﻿using System.Collections.Generic;
using System.Linq;
using Foxit.PDF;
using Foxit.PDF.PageElements;
using Sustainalytics.Utils;

namespace Sustainalytics.Reporting.Framework
{
    public class PdfGrid
    {
        public Page Page { get; set; }
        public string Name { get; set; }
        public float Left { get; set; }
        public float Top { get; set; }
        public float Width { get; set; }
        public float Height { get; set; }
        public int Rows { get; set; }
        public int Columns { get; set; }
        public bool ShowGridLines { get; set; }

        public List<IPdfPageElement> Children { get; set; }
        
        public PdfGrid()
        {
            Children = new List<IPdfPageElement>();
        }

        public void AddChildren(IPdfPageElement pageElement)
        {
            Children.Add(pageElement);
        }

        public void Draw()
        {
            Width = Page.Dimensions.Body.Width - Left - 5f;
            if (Height.NearlyEq(0.0f))
                Height = Page.Dimensions.Body.Height;

            var rowHeight = (int)Height/Rows;
            var columnWidth = (int)Width/Columns;
            var left = Left;
            var top = Top;

            for (var row = 1; row <= Rows; row++)
            {
                for (var column = 1; column <= Columns; column++)
                {
                    if (ShowGridLines)
                    {
                        Page.Elements.Add(new Rectangle(left, top, columnWidth, rowHeight, RgbColor.Blue,
                            RgbColor.White, 0.5f, LineStyle.Dash));
                    }

                    var elements = Children.Where(c => c.Row == row
                                                       && c.Column == column)
                        .ToList();

                    foreach (var element in elements)
                    {
                        element.Page = Page;
                        element.Left = left;
                        element.Top = top;

                        element.Draw();
                    }

                    left += columnWidth;
                }

                left = Left;
                top += rowHeight;
            }

        }
    }
}
